package com.zaofan.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zaofan.bean.Article;
import com.zaofan.dao.ArticleDao;
import com.zaofan.exception.ServiceException;
import com.zaofan.utils.WebUtils;

public class ArticleService {
	private ArticleDao articleDao = new ArticleDao();

	public void delete(Article article) {
		articleDao.del(article);
	}

	public void add(Article article) throws ServiceException {
		if (WebUtils.isEmpty(article.getTitle())) {
			throw new ServiceException("请输入文章标题");
		}
		if (WebUtils.isEmpty(article.getContent())) {
			throw new ServiceException("请输入文章内容");
		}
		article.setAddTime(new Date());
		articleDao.add(article);
	}

	public void update(Article article) {
		articleDao.update(article);
	}

	public void updateArticle(Article article) throws ServiceException {
		if (WebUtils.isEmpty(article.getId())) {
			throw new ServiceException("请输入文章id");
		}
		Article target = this.findById(article.getId());
		if (target == null) {
			throw new ServiceException("请输入文章id");
		}
		if (!WebUtils.isEmpty(article.getTitle())) {
			target.setTitle(article.getTitle());
		}
		if (!WebUtils.isEmpty(article.getContent())) {
			target.setContent(article.getContent());
		}
		articleDao.update(target);
	}

	public List<Article> findAll(Map<String, Object> params) {
		List<Article> data = articleDao.findAll(params);
		if (data == null) {
			data = new ArrayList<>();
		}
		return data;
	}

	public Long count(Map<String, Object> params) {
		return articleDao.count(params);
	}

	public Article findById(int id) {
		Map<String, Object> params = new HashMap<>();
		params.put("id", id + "");
		return articleDao.findOne(params);
	}

}
